import os.path

from ultralytics import YOLO

model = YOLO("best.pt")
# results = model("orange1.jpg")

#测试results结构
#print(results[0].boxes)
#box = results[0].boxes #results = [result_for_image_1] result返回的是每张图片的结果用于批量检测
# print("cls:",box.cls[0])
# print("label:",results[0].names[int(box.cls[0])])
#print("conf",box.conf)

# for box in results[0].boxes:
#     #print("conf:",float(box.conf))
#     print("xyxy:",box.xyxy.tolist())

def detect_defects(image_path):
    results = model.predict(
        source=image_path,
        save = True,
        project='D:\\lab\\detect\\report\\predict',  # 自定义保存到 outputs 文件夹
    )
    results = results[0]

    defects = []
    for box in results.boxes : #遍历所有边框
        cls_id = int(box.cls[0])
        label = results.names[cls_id]
        confidence = float(box.conf)
        xyxy = box.xyxy.tolist() #[[x,y,x,y]]
        xyxy = xyxy[0] #[x,y,x,y]

        defects.append({
            "label" : label,
            "confidence": round(confidence,3),
            "xyxy": [round(x,1) for x in xyxy]
        })

    return defects


#总结函数
def summarize_defects(defects: list[dict]):
    if not defects:
        return "未检测到任何缺陷"
    else:
        summary = f"检测到{len(defects)}个缺陷:"
        for d in defects:
            summary += f"{d['label']}(置信度:{d['confidence']})"
        return summary.strip("，") + "。"


#实现批处理
# def batch_detect_and_report(report_folder,image_folder):
#
#     if not os.path.exists(report_folder): #如果report_path不存在 就创建一个文件夹用于保存report
#         os.makedirs(report_folder)
#
#     for filename in os.listdir(image_folder):
#         if filename.lower().endswith()
#         defects = detect_defects(filename)




#
# if __name__ == "__main__":
#     defects = detect_defects("orange1.jpg")
#     print(defects)

